package com.wxy.xr.dao.impl;

import com.alibaba.druid.pool.DruidDataSourceFactory;
import com.wxy.xr.dao.BaseDao;
import com.wxy.xr.util.Strings;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;

import javax.sql.DataSource;
import java.lang.reflect.ParameterizedType;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;

public abstract class BaseDaoImpl<T> implements BaseDao<T> {
    protected static JdbcTemplate tpl;
    static {
        try {
            Properties properties=new Properties();
            properties.load(BaseDaoImpl.class.getClassLoader().getResourceAsStream("druid.properties"));
            DataSource ds= DruidDataSourceFactory.createDataSource(properties);
            tpl=new JdbcTemplate(ds);

        }catch (Exception e){
            e.printStackTrace();
        }
    }
    private String table=table();
    protected  String table(){
        ParameterizedType type= (ParameterizedType) getClass().getGenericSuperclass();
        Class beanCls= (Class) type.getActualTypeArguments()[0];
        String clsName=beanCls.getSimpleName();
        return Strings.underlineCase(clsName);
    }

    public boolean remove(Integer id) {
        String sql="delete from "+table+" where id = ?";
        return tpl.update(sql,id)>0;
    }


    public boolean remove(List<Integer> ids) {
        List<Object> args = new ArrayList<>();
        StringBuilder sql=new StringBuilder();
        sql.append("delete from ").append(table).append(" where id in (");
        for(Integer id : ids){
            args.add(id);
            sql.append("?, ");
        }
        sql.replace(sql.length()-2,sql.length(),")");
        return tpl.update(sql.toString(),args.toArray())>0;
    }
public int count(){
        String sql="select COUNT(*) FROM"+table;
        return tpl.queryForObject(sql,new BeanPropertyRowMapper<>(Integer.class));
}

}
